﻿using AuthCenter.Api.Read.Application.Command.RoleMenu;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using System.Security.Cryptography;

namespace AuthCenter.Api.Read.Application.Hander.RoleMenu
{
    public class GetMenuRoleIdHander:IRequestHandler<GetMenuRoleIdCommand,ApiResult<List<RoleMenuOutput>>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<RoleMenuModel> _roleMenuRepository;
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IBaseRepository<UserRoleModel> _userroleRepository;
        private readonly IMapper _mapper;
        public GetMenuRoleIdHander(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RoleMenuModel> roleMenuRepository, IMapper mapper, IBaseRepository<MenuModel> menuRepository, IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userroleRepository)
        {
            _roleRepository = roleRepository;
            _roleMenuRepository = roleMenuRepository;
            _mapper = mapper;
            _menuRepository = menuRepository;
            _userRepository = userRepository;
            _userroleRepository = userroleRepository;
        }
        /// <summary>
        /// 获取角色菜单
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public Task<ApiResult<List<RoleMenuOutput>>> Handle(GetMenuRoleIdCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<RoleMenuOutput>> res = new ApiResult<List<RoleMenuOutput>>();
            var roleIds = _roleMenuRepository.GetAll().Where(x => x.RId == request.rId && !x.IsDeleted);
            var model = _mapper.Map<List<RoleMenuOutput>>(roleIds);
            foreach (var item in model)
            {
                item.MId = _menuRepository.GetAll().Where(x => x.Id == item.MId).Select(x => x.Id).FirstOrDefault();
                item.MenuName = _menuRepository.GetAll().Where(x => x.Id == item.MId).Select(x => x.MenuName).FirstOrDefault();
            }
            res.Code = ApiEnums.OK;
            res.Message = "根据角色id获取菜单成功";
            res.Data = model;
            return Task.FromResult(res);

        }
    }
}
